//
//  Person.swift
//  SqlDemo
//
//  Created by 好米有易 on 2018/8/20.
//  Copyright © 2018年 好米有易. All rights reserved.
//

import UIKit

class Person: NSObject {

    var id: Int32 = 0
    var name : String?


    init(dict: [String: Any]) {
        super.init()

        name = dict["name"] as? String ?? ""

        if dict["id"] != nil {
            id = dict["id"] as! Int32
        }
    }

    override func setValue(_ value: Any?, forUndefinedKey key: String) {

    }

//    override var description: String {
//        let keys = ["id", "name"]
//
//        return dictionaryWithValues(forKeys: keys).description
//    }
//

   class func persons() -> [Person]? {
        let sql = "SELECT id, name FROM T_Person;"

        guard let array = SQLiteManager.shareManager.execRecordSet(sql: sql) else {

            return nil
        }
        var personsM = [Person]()

        for dict in array {
          personsM.append(Person(dict: dict))
            
        }

        return personsM

    }


    /// 删除数据
    ///
    /// - Returns: 返回是否删除成功
    func deletePerson() -> Bool {

        let sql = "DELETE FROM T_Person WHERE id = \(id)"

        return SQLiteManager.shareManager.execUpdate(sql: sql) > 0

    }


    /// 更新数据
    ///
    /// - Returns: 返回是否更新成功
    func updatePerson() -> Bool {

        let sql = "UPDATE T_Person SET name = '\(name!)' WHERE id = \(id)"

        return SQLiteManager.shareManager.execUpdate(sql: sql) > 0

    }


    /// 插入数据
    ///
    /// - Returns: 返回是否插入数据成功
    func insertPerson() -> Bool {

        let sql = "INSERT INTO T_Person (name) VALUES ('\(name!)');"

      return  SQLiteManager.shareManager.execInsert(sql: sql) > 0

    }

}
